#include "my_lvgl.h" //! 含arduino  main.h 硬件管脚  tft配置
static const uint16_t screenWidth = 240;
static const uint16_t screenHeight = 320; //*[横屏设置2-1]调换这里

TFT_eSPI tft = TFT_eSPI(screenWidth, screenHeight); /* TFT instance */

static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf[screenWidth * screenHeight / 10]; // 这个和下面那个一起改 可以改为20

lv_indev_t *indev_encoder;  //!编码器和按键的指针变量,设置group要用到

//* Display flushing  显示刷新的执行
void my_disp_flush(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p)
{
  uint32_t w = (area->x2 - area->x1 + 1);
  uint32_t h = (area->y2 - area->y1 + 1);

  tft.startWrite();
  tft.setAddrWindow(area->x1, area->y1, w, h);
  tft.pushColors((uint16_t *)&color_p->full, w * h, true);
  tft.endWrite();
  lv_disp_flush_ready(disp_drv);
}

static void encoder_read(lv_indev_drv_t *indev_drv, lv_indev_data_t *data)
{
  data->enc_diff = my_key_get(); //! 编码器和按键合一se版本  旋转方向  +1 0 和-1
  if (my_key_pressed())
  {                                        // 平时为1 按下为0
    data->state = LV_INDEV_STATE_RELEASED; // 没有键被按下
  }
  else
  {
    data->state = LV_INDEV_STATE_PRESSED; // 中键按下为0
  }
}

void myLvglInit()
{
  lv_init();
  my_key_init();      //! 编码器和按键初始化 pin设置为输入
  tft.begin();        /* TFT init */
  tft.setRotation(2); //*[横屏设置2-2] 设置为1*90或3*90   2是180度  上下颠倒

  lv_disp_draw_buf_init(&draw_buf, buf, NULL, screenWidth * screenHeight / 10);
  //*Initialize the display*/
  static lv_disp_drv_t disp_drv;
  lv_disp_drv_init(&disp_drv);
  disp_drv.hor_res = screenWidth;
  disp_drv.ver_res = screenHeight;
  disp_drv.flush_cb = my_disp_flush;
  disp_drv.draw_buf = &draw_buf;
  lv_disp_drv_register(&disp_drv);

  //*Initialize the input device*/
  static lv_indev_drv_t encoder_drv;                   // 创建结构体变量
  lv_indev_drv_init(&encoder_drv);                     // 初始化 成员赋初值
  encoder_drv.type = LV_INDEV_TYPE_ENCODER;            // 编码器模式驱动按键更好用
  encoder_drv.read_cb = encoder_read;                  /* 回调函数：通过这个函数读取输入设备的值 */
  indev_encoder = lv_indev_drv_register(&encoder_drv); // 返回的指针保留为全局变量设置group要用到
}